package com.sylar.lelepub.adapter;

import java.util.ArrayList;

import android.content.Context;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import com.sylar.lelepub.R;
import com.sylar.lelepub.domain.CityInfo;

public class CityAdapter extends BaseAdapter {

	private Context context;
	private ArrayList<CityInfo> modes;

	public CityAdapter(Context context, ArrayList<CityInfo> list) {
		this.context = context;
		this.modes = list;
	}

	@Override
	public int getCount() {
		return modes != null && modes.size() > 0 ? modes.size() : 0;
	}

	@Override
	public Object getItem(int position) {
		// TODO Auto-generated method stub
		return modes != null && modes.size() > 0 ? modes.get(position) : null;
	}

	@Override
	public long getItemId(int position) {
		// TODO Auto-generated method stub
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		ViewHolder holder;
		if (convertView == null) {
			holder = new ViewHolder();
			convertView = LayoutInflater.from(context).inflate(
					R.layout.city_item, null);

			holder.fistAlphaTextView = (TextView) convertView
					.findViewById(R.id.tai_first_alpha);
			holder.nameTextView = (TextView) convertView
					.findViewById(R.id.tai_name);

			convertView.setTag(holder);
		} else {

			holder = (ViewHolder) convertView.getTag();

		}

		if (modes != null && modes.size() > 0) {
			CityInfo cityInfo = modes.get(position);
			if (cityInfo != null) {

				// 名称
				String name = cityInfo.name;
				if (!TextUtils.isEmpty(name)) {
					holder.nameTextView.setText(name);
				}

				// 首字母(前后两项对比字母是否相同，如果相同则过滤，否则添加进来)
				String currentAlpha = cityInfo.shortName.substring(0, 1)
						.toUpperCase();
				CityInfo info = (position - 1) >= 0 ? modes.get(position - 1)
						: null;
				String previewStr = "";
				if (info != null) {
					previewStr = info.shortName.substring(0, 1).toUpperCase();
				}

				if (!previewStr.equals(currentAlpha)) {
					holder.fistAlphaTextView.setVisibility(View.VISIBLE);
					if (currentAlpha.equals("热")) {
						holder.fistAlphaTextView.setText(currentAlpha+"门城市");
					}else {
						holder.fistAlphaTextView.setText(currentAlpha);
					}
				} else {
					holder.fistAlphaTextView.setVisibility(View.GONE);
				}
			}
		}

		return convertView;
	}

	class ViewHolder {
		TextView fistAlphaTextView;
		TextView nameTextView;
	}

}
